package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CertificateNoContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

public class AddEmpoyeeLoanDetailFragment extends EmpoyeeLoanFragment {
  public static final String EXTRA_CODE = "com.isunland.managesystem.ui.EXTRA_CODE";
  protected static final String TAG = AddEmpoyeeLoanDetailFragment.class.getSimpleName();
  private static final int REQUEST_RENAME = 2;//重命名
  private String code;
  private CertificateNoContent mNoContent;
  private Boolean isNumber;//判断是否是数字

  @Override protected void setTitle() {
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.employeeLoan_add);
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    code = getArguments().getString(EXTRA_CODE);
    //自动生成id
    id = UUID.randomUUID().toString();
    super.onCreate(savedInstanceState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    //		inflater.inflate(R.menu.menu_confirm, menu);
    inflater.inflate(R.menu.menu_save_submit, menu);
    menu.getItem(1).setTitle(R.string.saveAndSubmit);
  }

  protected void initData() {
    //		//获取单据编号

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ADD_EMPLOYEE_LOAN_DETAIL);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("certificateCode", code);
    params.put("userJobNo", mCurrentUser.getJobNumber());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        CertificateNoContent[] array = new Gson().fromJson(arg0, CertificateNoContent[].class);
        mNoContent = array[0];
        Log.i("hhhhhhh", mNoContent.toString());
        tvcertificateNo.setText(mNoContent.getCertificateNo());
        tvsumBorrow.setText(mNoContent.getSumBorrow());
        tvloanPerson.setText(mCurrentUser.getRealName());
        tvloanProposer.setText(mCurrentUser.getRealName());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
        tvloanDate.setText(format.format(new Date()));

        //开户行
        etpayeeBank.setText(mNoContent.getPayeeBank());
        etpayeeAccname.setText(mNoContent.getPayeeAccname());
        etpayeeAccount.setText(mNoContent.getPayeeAccount());
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub
      }
    });

    //		//查看附件
    //
    //			mTvExtra.setOnClickListener(new OnClickListener() {
    //
    //				@Override
    //				public void onClick(View v) {
    //					if (!TextUtils.isEmpty(mDocPath)) {
    //					ExtraDownLoadDialogFragment dialog = ExtraDownLoadDialogFragment.newInstance("", mDocPath);
    //					FragmentManager fm = getActivity().getSupportFragmentManager();
    //					dialog.show(fm, "");
    //					}
    //				}
    //			});
  }

  // 菜单点击事件
  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      // 保存
      case R.id.menu_item_save:
        if (TextUtils.isEmpty(etpoutAmount.getText().toString())) {
          Toast.makeText(getActivity(), R.string.loanNotNull, Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(tvcertificateNo.getText().toString())) {
          Toast.makeText(getActivity(), R.string.noCertificateNo, Toast.LENGTH_SHORT).show();
        } else {
          /**
           * 修改添加附件
           */
          //判断有无附件
          if (TextUtils.isEmpty(mFilePath)) {
            //附件为空时
            volleyPostSave(SAVE);
          } else {
            //附件不为空时，先上传附件，再保存数据
            //					//自动生成id
            //			    id=UUID.randomUUID().toString();
            volleyExtra(SAVE);
          }
        }

        break;
      //启动流程
      case R.id.menu_item_submit:

        if (TextUtils.isEmpty(etpoutAmount.getText().toString())) {
          Toast.makeText(getActivity(), R.string.loanNotNull, Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(tvcertificateNo.getText().toString())) {
          Toast.makeText(getActivity(), R.string.noCertificateNo, Toast.LENGTH_SHORT).show();
        } else {
          /**
           * 修改添加附件
           */
          //判断有无附件
          if (TextUtils.isEmpty(mFilePath)) {
            //附件为空时
            //                        volleyPostSave();
            showDialog(SAVE_START);
          } else {
            //附件不为空时，先上传附件，再保存数据
            //					//自动生成id
            //			    id=UUID.randomUUID().toString();
            volleyExtra(SAVE_START);
          }
        }

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog =
        BaseConfirmDialogFragment.newInstance(R.string.cannotEdit, R.string.hintMessage);
    FragmentManager fm = getActivity().getSupportFragmentManager();
    dialog.setTargetFragment(this, requestCode);
    dialog.show(fm, "");
  }

  private void volleyExtra(int requestCode) {

    new FileNetWorkUtil(getActivity()).upLoadFile(mFilePath, ApiConst.URL_UPLOAD_FILE,
        "r_expense_inexp_main", id, new myUpLoadHandler(requestCode), false);
  }

  private class myUpLoadHandler extends AsyncHttpResponseHandler {
    private int requestCode;

    public myUpLoadHandler(int requestCode) {
      super();
      this.requestCode = requestCode;
    }

    @Override public void onStart() {
      MyUtils.showDialogLoading(getActivity());

      super.onStart();
    }

    @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
      MyUtils.dismissDialog();
      Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
    }

    @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
      //			MyUtils.dismissDialog();
      LogUtil.i("arg2==" + new String(arg2));
      try {

        SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);
        if (result == null) {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), R.string.wrong_data, Toast.LENGTH_SHORT).show();
        }
        if (result != null && result.getResult() != null && result.getResult().equals("1")) {
          //					Toast.makeText(getActivity(), R.string.fileUploadSuccess, Toast.LENGTH_SHORT).show();
          // 上传成功,再上传数据
          selcurFile = result.getMessage().toString();
          selcurFile = selcurFile.replace("\\", "/");
          LogUtil.i("selcurFile==" + selcurFile);
          volleyPostSave(requestCode);
        } else {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), result.getMessage().toString(), Toast.LENGTH_SHORT).show();
          //判断是重名导致上传失败.
          //1.获取文件名.
          //2.重命名文件.
          //3.重新上传.
          //					result.getMessage()!=null&&message.equsals
          //有同名文件的时候
          //					Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
          //					Toast.makeText(getActivity(),result.getMessage().toString(), Toast.LENGTH_SHORT).show();
          //					DialogFragment dialog = null;
          //					FragmentManager fm = getActivity().getSupportFragmentManager();
          //					dialog = BaseConfirmDialogFragment
          //							.newInstance("已上传存在同名文件,请修改文件名！",R.string.restart_title);
          //					dialog.setTargetFragment(AddEmpoyeeLoanDetailFragment.this,
          //							REQUEST_RENAME);
          //					dialog.show(fm, "");

        }
      } catch (JsonSyntaxException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      } catch (NotFoundException e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      }
    }
  }

  private void volleyPostSave(final int requestCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PESONAL_SAVE);

    HashMap<String, String> params = new HashMap<String, String>();

    HashMap<String, String> paramsItem = new HashMap<String, String>();
    paramsItem.put("id", id);//保存时 id本地自动生成

    paramsItem.put("certificateNo", mNoContent.getCertificateNo());
    paramsItem.put("expenseDesc", etexpenseDesc.getText().toString());
    paramsItem.put("poutAmount", etpoutAmount.getText().toString());
    paramsItem.put("sumBorrow", tvsumBorrow.getText().toString());

    paramsItem.put("receiverName", tvloanPerson.getText().toString());
    paramsItem.put("receiverId", mCurrentUser.getJobNumber().toString());

    paramsItem.put("applicantName", tvloanProposer.getText().toString());
    paramsItem.put("applicantId", mCurrentUser.getJobNumber().toString());

    //登记人
    params.put("regStaffName", tvloanProposer.getText().toString());
    params.put("regStaffId", mCurrentUser.getJobNumber().toString());

    paramsItem.put("applyTime", tvloanDate.getText().toString());

    paramsItem.put("dataStatus", "new");
    paramsItem.put("ifReturnLoan", "F");

    paramsItem.put("inAmount", "0");
    paramsItem.put("billAmount", "0");
    paramsItem.put("nobillAmount", "0");
    paramsItem.put("toutAmount", "0");
    paramsItem.put("ifOffBorrow", "F");
    paramsItem.put("offBorrow", "0");
    paramsItem.put("sumPrebill", "0");
    paramsItem.put("replenishAmount", "0");
    paramsItem.put("billNo", "");

    //费用归属
    paramsItem.put("fownerkindName", "公司费用");//分类
    paramsItem.put("fownerkindCode", "01");//分类code，默认是公司费用
    paramsItem.put("appobjectName", mCurrentUser.getMemberName());//对象
    paramsItem.put("appobjectId", mCurrentUser.getMemberCode());//对象id,公司会员编码
    //开户行
    if (!TextUtils.isEmpty(etpayeeBank.getText().toString())) {
      paramsItem.put("payeeBank", etpayeeBank.getText().toString());
    } else {
      paramsItem.put("payeeBank", "");
    }
    if (!TextUtils.isEmpty(etpayeeAccname.getText().toString())) {
      paramsItem.put("payeeAccname", etpayeeAccname.getText().toString());
    } else {
      paramsItem.put("payeeAccname", "");
    }
    if (!TextUtils.isEmpty(etpayeeBank.getText().toString())) {
      paramsItem.put("payeeAccount", etpayeeAccount.getText().toString());
    } else {
      paramsItem.put("payeeAccount", "");
    }

    //新增附件上传
    paramsItem.put("filePath", selcurFile);
    paramsItem.put("fileOriginalName", mfileName);
    if (!TextUtils.isEmpty(selcurFile)) {
      paramsItem.put("id", id);
    }
    String test = new JSONObject(paramsItem).toString();

    params.put("json", test);
    LogUtil.i(test);
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("certificateCode", code);
    params.put("regJobNo", mCurrentUser.getJobNumber());
    params.put("type", "mobile");
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        LogUtil.i("arg0==" + arg0);
        SuccessMessage[] result = new Gson().fromJson(arg0, SuccessMessage[].class);
        SuccessMessage workProcess = result[0];
        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          if (SAVE == requestCode) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else if (SAVE_START == requestCode) {
            //启动流程
            volleyStart();
          }
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  // 启动流程方法
  private void volleyStart() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_START_UP);

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("isList", "1");
    params.put("id", id);
    /**
     * 添加界面获取不到flowFlag
     * */
    //        params.put("recFlowKey", mEmployeeLoanContent.getFlowFlag());
    params.put("certificateCode", code);
    LogUtil.i("启动流程params===" + params.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        LogUtil.i("启动流程==" + arg0);
        MyUtils.dismissDialog();
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == workProcess || null == workProcess.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();

          //重新启动时的错误log日志
          LogUtil.e(workProcess.getMessage().toString());

          return;
        }
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          MyUtils.dismissDialog();
          Toast.makeText(getActivity(), R.string.failstartup, Toast.LENGTH_SHORT).show();
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == SAVE_START) {
      volleyPostSave(SAVE_START);
      return;
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  // fragment之间传值
  public static AddEmpoyeeLoanDetailFragment newInstance(String code) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CODE, code);
    AddEmpoyeeLoanDetailFragment fragment = new AddEmpoyeeLoanDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
